#include "register.h"
#include "ui_register.h"

Register::Register(QWidget *parent,Netserver_udp *getserver) :
    QWidget(parent),
    ui(new Ui::Register)
{
    ui->setupUi(this);
    m_StartNetServer = getserver;
    m_Timer = new QTimer(this);

    m_Sex = "boy ";

    connect(ui->pBrefer,SIGNAL(clicked()),this,SLOT(m_Refer()));
    connect(ui->rBboy,SIGNAL(clicked()),this,SLOT(m_SetBoy()));
    connect(ui->rBgirl,SIGNAL(clicked()),this,SLOT(m_SetGirl()));
}

Register::~Register()
{
    delete ui;
    delete m_Timer;
}

void Register::m_SetBoy()
{
    m_Sex = "boy ";
}

void Register::m_SetGirl()
{
    m_Sex = "girl";
}

void Register::m_Refer()
{
    QByteArray send_data;

    if(true == m_Error.m_IllegalCharCheck("新用户名", ui->lEnewusername->text(),6))
        return;
    if(true == m_Error.m_IllegalCharCheck("密码",ui->lEpassword->text(),6))
        return;
    if(false == ui->lEpassword->text().contains(ui->lEconfirmpassword->text())){
        m_Error.m_ErrorPlay("确认密码","确认密码与密码不同");
        return;
    }

    send_data.append(SPECIAL_REGISTER);//
    send_data += ui->lEnewusername->text();
    send_data += ui->lEpassword->text();
    m_Error.m_Format(&send_data, m_StartNetServer->m_GetIp(), 15, ' ');
    send_data += m_Sex;
    m_Error.m_Format(&send_data, ui->dateEdit->text(), 8, ' ');

    qDebug()<<"register senddata:"<<send_data;
    disconnect(ui->pBrefer,SIGNAL(clicked()),this,SLOT(m_Refer()));
    m_StartNetServer->m_SendMessageProcess(send_data);

    m_Timer->start(5000);//10s timer
    connect(m_Timer,SIGNAL(timeout()),this,SLOT(m_TimeroutProcess()));
    connect(m_StartNetServer->m_UdpDescribe,SIGNAL(readyRead()),this,SLOT(m_WaitProcess()));
}

void Register::m_TimeroutProcess()
{
    m_Error.m_ErrorPlay("超时","连接服务器超时");
    m_Timer->stop();
    disconnect(m_StartNetServer->m_UdpDescribe,SIGNAL(readyRead()),this,SLOT(m_WaitProcess()));
    connect(ui->pBrefer,SIGNAL(clicked()),this,SLOT(m_Refer()));
}

void Register::m_WaitProcess()
{
    QByteArray recive_data = m_StartNetServer->m_ReciveMessageProcess();
    if(SPECIAL_LOGIN != recive_data.at(1))
        return;
    m_Timer->stop();
    switch(recive_data.at(2))
    {
    case SPECIAL_REFER_EXIST_NAME://用户不存在
        m_Error.m_ErrorPlay("注册","用户已存在");;
        break;
    case SPECIAL_REFER_SUCCESS://成功入口
        this->close();
        break;
    default:
        m_Error.m_ErrorPlay("register","Recive user data Error!");
    }
    connect(ui->pBrefer,SIGNAL(clicked()),this,SLOT(m_Refer()));
}
